package main

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"sync"
)

// func Trace(name string) func() {
// 	println("enter: ", name)
// 	return func() {
// 		println("exit: ", name)
// 	}
// }

// 改为自动获取函数名版本->
func Trace1() func() {
	pc, _, _, ok := runtime.Caller(1)
	if !ok {
		panic("not found caller")
	}

	fn := runtime.FuncForPC(pc)
	name := fn.Name()

	gid := curGoroutineID()

	fmt.Printf("routine[%05d]: enter: [%s]\n", gid, name)
	return func() {
		fmt.Printf("routine[%05d]: exit: [%s]\n", gid, name)
	}
}

// 改为更有层次性的版本
func printTrace(id uint64, name, arrow string, indent int) {
	indents := ""
	for i := 0; i < indent; i++ {
		indents += "    "
	}
	fmt.Printf("g[%05d]:%s%s%s\n", id, indents, arrow, name)
}

var mu sync.Mutex
var m = make(map[uint64]int)

func Trace() func() {
	pc, _, _, ok := runtime.Caller(1)
	if !ok {
		panic("not found caller")
	}

	fn := runtime.FuncForPC(pc)
	name := fn.Name()

	gid := curGoroutineID()

	mu.Lock()
	indent := m[gid]
	m[gid] = indent + 1
	mu.Unlock()

	printTrace(gid, name, "->", indent+1)

	return func() {
		mu.Lock()
		indent := m[gid] // 获取当前gid对应的缩进层次
		m[gid] = indent - 1
		mu.Unlock()
		printTrace(gid, name, "<-", indent)
	}
}

func foo() {
	// defer Trace("foo")()
	defer Trace()()
	bar()
}

func bar() {
	// defer Trace("bar")()
	defer Trace()()
}

func A1() {
	defer Trace()()
	B1()
}

func B1() {
	defer Trace()()
	C1()
}

func C1() {
	defer Trace()()
	D()
}

func D() {
	defer Trace()()
}

func A2() {
	defer Trace()()
	B2()
}

func B2() {
	defer Trace()()
	C2()
}

func C2() {
	defer Trace()()
	D()
}

func main() {
	// defer Trace("main")()
	// defer Trace()()
	// foo()

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		A2()
		wg.Done()
	}()

	A1()
	wg.Wait()
}

// 为了防止 Goroutine ID 的滥用, Go核心团队故意没有将 Goroutine ID 暴露给开发者。
// 参考 $GOROOT/src/net/http/h2_bundle.go 的方法 func http2curGoroutinueID() uint64

/**
var http2goroutineSpace = []byte("goroutine ")

func http2curGoroutinueID() uint64 {
	bp := http2littleBuf.Get().(*[]byte)
	defer http2littleBuf.Put(bp)
	b := *bp
	b = b[:runtime.Stack(b, false)]
	// Parse the 4707 out of "goroutine 4707 ["
	b = bytes.TrimPrefix(b, http2goroutineSpace)
	i := bytes.IndexByte(b, ' ')
	if i < 0 {
		panic(fmt.Sprintf("No space found in %q", b))
	}
	b = b[:i]
	n, err := http2parseUnitBytes(b, 10, 64)
	if err != nil {
		panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
	}
	return n
}
**/

var goroutineSpace = []byte("goroutine ")

func curGoroutineID() uint64 {
	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	// Parse the 4707 out of "goroutine 4707 ["
	b = bytes.TrimPrefix(b, goroutineSpace)
	i := bytes.IndexByte(b, ' ')
	if i < 0 {
		panic(fmt.Sprintf("No space found in %q", b))
	}
	b = b[:i]
	n, err := strconv.ParseUint(string(b), 10, 64)
	if err != nil {
		panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
	}
	return n
}
